<template>
  <aside class="main-sidebar" id="main-sidebar">
    <section class="sidebar">
      <!-- 搜索 -->
      <div action="#" method="get" class="sidebar-form" v-if="menu_search">
        <div class="input-group">
          <input type="text" name="q" class="form-control" v-model="menu_search_value" :placeholder="tr.search+tr.menu">
          <span class="input-group-btn">
            <button type="submit" name="search" id="search-btn" class="btn btn-flat">
              <i class="fa fa-search"></i>
            </button>
          </span>
        </div>
      </div>

      <!-- 全展开（保持原逻辑） -->
      <ul v-if="menu_expand_all" class="sidebar-menu" data-widget="tree" data-api="tree" data-accordion="0">
        <li v-for="action in filted_menu" :key="action.label" :class="{active:true,treeview:action.submenu}">
          <a :href="action.url">
            <i v-html="action.icon"></i>
            <span v-text="action.label"></span>
            <span v-if="action.submenu" class="pull-right-container">
              <i class="fa fa-angle-left pull-right"></i>
            </span>
          </a>
          <ul v-if="action.submenu" class="treeview-menu">
            <li v-for="subact in action.submenu" :key="subact.label" :class="{'active':is_active(subact)}">
              <a :href="subact.url">
                <i class="fa fa-circle-o"></i>
                <span v-text="subact.label"></span>
              </a>
            </li>
          </ul>
        </li>
      </ul>

      <!-- 可收缩 --><!-- 切换折叠/展开时强制重建，清理旧事件 -->
      <ul
          v-else
          :key="menuKey"
      class="sidebar-menu"
      :class="{'submenu-click': submenuShow==='click' && sidebarCollapsed}"
      :data-widget="(submenuShow==='hover' || !sidebarCollapsed) ? 'tree' : null"
      >
      <li
          v-for="(action, idx) in filted_menu"
          :key="action.label"
          :class="{
            active: is_active(action),
            treeview: action.submenu,
            /* 只在 折叠+click 模式下由我们控制展开；展开态完全交给 AdminLTE */
            'menu-open': submenuShow==='click' && sidebarCollapsed && openIndex===idx,
            'open-by-click': submenuShow==='click' && sidebarCollapsed && openIndex===idx
          }"
      >
        <a
            :href="action.url"
            :title="(submenuShow==='click' && sidebarCollapsed) ? action.label : null"
            @click="onMainClick(action, idx, $event)"
        >
          <i v-html="action.icon"></i>
          <span v-text="action.label"></span>
          <span v-if="action.submenu" class="pull-right-container">
              <i class="fa fa-angle-left pull-right"></i>
            </span>
        </a>

        <!-- 二级 -->
        <ul
            v-if="action.submenu"
            class="treeview-menu"
            :style="submenuStyle(idx)"
        >
          <li
              v-for="subact in action.submenu"
              :key="subact.label"
              :class="{'active':is_active(subact),treeview:subact.submenu}"
          >
            <a :href="subact.url">
              <i class="fa fa-circle-o"></i>
              <span v-text="subact.label"></span>
              <span v-if="subact.submenu" class="pull-right-container">
                  <i class="fa fa-angle-left pull-right"></i>
                </span>
            </a>

            <!-- 三级 -->
            <ul v-if="subact.submenu" class="treeview-menu">
              <li v-for="sub_subact in subact.submenu" :key="sub_subact.label" :class="{'active':is_active(sub_subact)}">
                <a :href="sub_subact.url">
                  <i class="fa fa-square-o"></i>
                  <span v-text="sub_subact.label"></span>
                </a>
              </li>
            </ul>
          </li>
        </ul>
      </li>
      </ul>
    </section>
  </aside>
</template>

<script>
export default {
  props:{
    menu:{},
    menu_expand_all:{},
    menu_search:{},
    menu_search_value:{},
    submenuShow: {
      type: String,
      default: 'hover', // 'hover' | 'click'
      validator: v => v==='hover' || v==='click'
    }
  },
  data(){
    return {
      tr: cfg.tr,
      openIndex: null,
      sidebarCollapsed: false,
      renderTick: 0,          // 改变它触发 <ul> 重建
      _onSidebarSwitch: null
    }
  },
  computed:{
    filted_menu(){
      var tmp_menus = ex.copy(this.menu)
      if(this.menu_search_value == '') return tmp_menus
      var self=this
      var valid_menus = ex.filter(tmp_menus, m =>
          m.label.toLowerCase().includes(self.menu_search_value.toLowerCase())
      )
      ex.each(tmp_menus, function(menu){
        if(menu.submenu && menu.submenu.length){
          if(!ex.isin(menu, valid_menus)){
            ex.remove(menu.submenu, act =>
                !act.label.toLowerCase().includes(self.menu_search_value.toLowerCase())
            )
          }
        }
      })
      ex.remove(tmp_menus, function(menu){
        if (ex.isin(menu, valid_menus)) return false
        return !(menu.submenu && menu.submenu.length)
      })
      return tmp_menus
    },
    menuKey(){
      return `${this.submenuShow}-${this.sidebarCollapsed ? 'c' : 'e'}-${this.renderTick}`
    }
  },
  methods:{
    is_active(action){
      if (action.url == location.pathname) return true
      if (action.url == location.pathname + location.search) return true
      if (action.submenu){
        for (let i=0;i<action.submenu.length;i++){
          if (this.is_active(action.submenu[i])) return true
        }
      }
      return false
    },
    leve2_url(action){
      return this.is_active(action) ? location.pathname : ''
    },

    onMainClick(action, idx, e){
      // 仅当：click 模式 + 折叠状态 + 有子菜单 时拦截（展开态不拦截，交给 AdminLTE）
      if (!(this.submenuShow === 'click' && this.sidebarCollapsed && action.submenu)) return
      e.preventDefault()
      e.stopPropagation()
      this.openIndex = (this.openIndex === idx) ? null : idx
    },

    submenuStyle(idx){
      if (!(this.submenuShow === 'click' && this.sidebarCollapsed)) return {}
      if (this.openIndex === idx){
        return {
          display: 'block',
          position: 'absolute',
          left: '50px',
          top: '0',
          minWidth: '180px',
          zIndex: 1050
        }
      }
      return {}
    },

    /* 初始化/重绑 AdminLTE tree（只在展开态调用） */
    initTree(){
      if (this.sidebarCollapsed) return
      this.$nextTick(() => {
        try{
          if (window.$) {
            const $menu = window.$(this.$el).find('.sidebar-menu[data-widget="tree"]')
            if ($menu.length && $menu.tree) $menu.tree()
          }
        }catch(e){}
      })
    },

    /* 根事件：外部切换折叠（this.$root.$emit('sidebar-collapse-switch')） */
    handleSidebarSwitch(){
      const collapsedNow = document.body.classList.contains('sidebar-collapse')
      if(collapsedNow){
        ex.localSet(`${engine_name}.sidebar-collapse`,true)
        // sessionStorage.setItem(`${engine_name}.sidebar-collapse`,true);
      }else{
        ex.localSet(`${engine_name}.sidebar-collapse`,false)
        // sessionStorage.removeItem(`${engine_name}.sidebar-collapse`);
      }

      if (collapsedNow !== this.sidebarCollapsed){
        this.sidebarCollapsed = collapsedNow
        this.openIndex = null
        // 切换时强制重建，清理旧绑定
        this.renderTick++
        // 若切到“展开态”，重绑 AdminLTE 的 tree
        if (!collapsedNow) this.initTree()
      } else {
        this.openIndex = null
      }
    }
  },
  mounted(){

    // var collapse = sessionStorage.getItem(`${engine_name}.sidebar-collapse`);
    var collapse = ex.localGet(`${engine_name}.sidebar-collapse`,undefined)
    if(collapse !=undefined){
      if(collapse){
        document.body.classList.add('sidebar-collapse')
      }else{
        document.body.classList.remove('sidebar-collapse')
      }

    }
    // 初始同步 + 在初始即展开的情况下主动初始化一次 tree
    this.sidebarCollapsed = document.body.classList.contains('sidebar-collapse')
    if (!this.sidebarCollapsed) this.initTree()

    // 监听根事件
    this._onSidebarSwitch = () => this.handleSidebarSwitch()
    this.$root.$on('sidebar-collapse-switch', this._onSidebarSwitch)
  },
  beforeDestroy(){
    if (this._onSidebarSwitch) this.$root.$off('sidebar-collapse-switch', this._onSidebarSwitch)
  }
}
</script>

<!-- 覆盖样式：仅在“折叠 + click 模式”下生效；不加 scoped -->
<style lang="scss">
body.sidebar-collapse #main-sidebar .sidebar-menu.submenu-click > li:hover > .treeview-menu{
  display: none !important;
}
body.sidebar-collapse #main-sidebar .sidebar-menu.submenu-click > li:hover > a > span{
  display: none !important;
}
body.sidebar-collapse #main-sidebar .sidebar-menu.submenu-click > li:hover > a > .pull-right-container{
  display: none !important;
}
body.sidebar-collapse #main-sidebar .sidebar-menu.submenu-click > li{
  position: relative;
}
body.sidebar-collapse #main-sidebar .sidebar-menu.submenu-click > li.open-by-click > .treeview-menu{
  display: block !important;
  position: absolute;
  left: 50px;
  top: 0;
  min-width: 180px;
  margin-left: 0;
  z-index: 1050;
  border-radius: 4px;
  box-shadow: 0 6px 12px rgba(0,0,0,.175);
}
</style>
